package com.bluegalaxy.sitescore.common;

import ch.qos.logback.core.util.ContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2018/9/14 0014.
 */
public class UploadUtil {

    // 取出虚拟目录的访问路径
   protected static String virtualDir = "http://ss.lzruil.cn/fileUpload";//设置你虚拟目录访问路径

    private static final Logger log = LoggerFactory.getLogger(UploadUtil.class);
    private UploadUtil() {
    }
    private static SimpleDateFormat fullSdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    private static SimpleDateFormat folder = new SimpleDateFormat(
            "yyyy" + File.separator + "MM" + File.separator + "dd");
    /**
     * 返回yyyy File.separator MM File.separator dd格式的字符串
     *
     * @return
     */
    public static String getFolder() {
        return folder.format(new Date());
    }
    /**
     * 文件上传
     *
     * @param srcName
     * 原文件名
     * @param input
     * 要保存的输入流
     * @return 返回要保存到数据库中的路径
     */
    public static String writeFile(String srcName, String uploadDir, InputStream input) throws IOException {
        log.info(srcName);
        String filename = "";
        // 得到要上传的文件路径
        filename =uploadDir + File.separator + fullSdf.format(new Date())+File.separator + srcName;
        // 得到将要保存到数据中的路径
        String savePath = filename.replace(uploadDir, "");
        savePath = virtualDir + savePath.replace("\\", "/");
        File file = new File(filename);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(file);
        // 一次30kb
        byte[] readBuff = new byte[1024 * 30];
        int count = -1;
        while ((count = input.read(readBuff, 0, readBuff.length)) != -1) {
            fos.write(readBuff, 0, count);
        }
        fos.flush();
        fos.close();
        input.close();
        return savePath;
    }
}
